<template>
  <div class="search">
    <h1>公共设备管理</h1>
    <hr style="border: 1px solid rgb(240, 240, 240)" />
    <span>设备分类</span>
    <el-select
      v-model="equipment_classify"
      style="width: 200px"
      placeholder="设备分类"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <span>设备名称/编号</span>
    <el-input
      v-model="equipment_name"
      style="width: 200px; margin-right: 5%"
      placeholder="请输入"
    />
    <el-button type="primary" @click="fetchData">查询</el-button>
    <el-button type="default" @click="resetFilters">重置</el-button>
  </div>
  <div class="page">
    <div class="page-header">
      <div class="page-header-left">
        <span>设备列表</span>
      </div>
      <div class="page-header-right">
        <el-button type="primary" style="margin-top: 1rem" @click="handleAddNew"
          >+&nbsp;新建</el-button
        >
        <el-button
          type="default"
          style="margin-top: 1rem; margin-right: 3rem"
          @click="deleteDialog = true"
          >批量删除</el-button
        >
        <el-dialog v-model="deleteDialog" title="警告" width="500" align-center>
          <span>是否删除选中的信息，该操作不可撤回！</span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteDialog = false">取消</el-button>
              <el-button type="primary" @click="deleteByIds"> 确认 </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column label="设备分类" prop="group" />
      <el-table-column label="设备名称" prop="name" />
      <el-table-column label="设备编号" prop="deviceNum" />
      <el-table-column label="品牌型号" prop="style" />
      <el-table-column label="所在区域" prop="area" />
      <el-table-column label="设备状态" prop="status" />
      <el-table-column label="维护人员" prop="fixer" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        style="margin-bottom: 2rem"
        background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecords"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const loading = ref(false);
const deleteDialog = ref(false);
const selectRows = ref([]);

const router = useRouter(); // 获取路由实例

// 表单选择框数据
const equipment_classify = ref("");
const equipment_name = ref("");
const options = [
  { value: "电梯", label: "电梯" },
  { value: "健身器材", label: "健身器材" },
  { value: "路灯", label: "路灯" },
  { value: "垃圾桶", label: "垃圾桶" },
  { value: "灭火器", label: "灭火器" },
];

// 分页相关
const pageNum = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示条数
const totalRecords = ref(0); // 总记录数
const tableData = ref([]); // 存放查询结果

// 查询数据
const fetchData = () => {
  const queryParams = {
    name: equipment_name.value,
    group: equipment_classify.value,
    page: pageNum.value,
    pageSize: pageSize.value,
  };

  loading.value = true;
  axios
    .get("http://localhost:8080/publicDevice/page", {
      headers: {
        Authorization: localStorage.getItem("token"),
      },
      params: queryParams,
    })
    .then((response) => {
      if (response.data.code === 1) {
        totalRecords.value = response.data.data.total; // 更新总记录数
        tableData.value = response.data.data.records; // 更新表格数据
        loading.value = false;
      } else {
        console.error(response.data.msg);
      }
    })
    .catch((error) => {
      console.error("请求数据失败", error);
    });
};

// 重置过滤器
const resetFilters = () => {
  equipment_classify.value = "";
  equipment_name.value = "";
  fetchData(); // 重置后重新查询
};

const handleSelectionChange = (selectedRows) => {
  selectRows.value = selectedRows;
};

// 分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchData(); // 页大小变化后重新查询
};

// 页码变化
const handlePageChange = (newPage) => {
  pageNum.value = newPage;
  fetchData(); // 页码变化后重新查询
};

// 新建设备
const handleAddNew = () => {
  router.push("/backend/equipment/newDevice"); // 跳转到新建设备页面
};

// 编辑设备
const handleEdit = (row) => {
  console.log("编辑设备:", row.id);
  // 路由跳转并传递设备 id
  router.push({
    path: "/backend/equipment/newDevice", // 假设此路径是设备编辑页面
    query: { id: row.id }, // 传递设备的 id
  });
};

// 删除设备
const handleDelete = (id) => {
  // 删除设备
  axios
    .delete(`http://localhost:8080/publicDevice/${id}`, {
      headers: {
        Authorization: localStorage.getItem("token"),
      },
    })
    .then((response) => {
      if (response.data.code === 1) {
        fetchData(); // 删除成功后刷新设备列表
      } else {
        console.error("删除失败:", response.data.msg);
      }
    })
    .catch((error) => {
      console.error("删除设备失败:", error);
    });
};

const deleteByIds = () => {
  if (selectRows.value.length === 0) {
    ElMessage({
      message: "请选择要删除的信息",
      type: "warning",
    });
    deleteDialog.value = false;
    return;
  }

  const config = {
    url: "http://localhost:8080/publicDevice/deleteByIds",
    method: "DELETE",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
    data: selectRows.value.map((item) => item.id),
  };

  const response = axios(config);
  response
    .then((data) => {
      if (data.data.code === 1) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        setTimeout(() => {
          fetchData();
        }, 2000);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  deleteDialog.value = false;
};

// 初始加载
onMounted(() => {
  fetchData(); // 组件挂载后默认查询
});
</script>

<style scoped>
.search {
  background-color: white;
  padding-bottom: 2rem;
  height: auto;
  margin-top: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin-top: 2rem;
  margin-left: 3rem;
  margin-right: 1rem;
  height: 24px;
}

.page {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  margin-top: 2rem;
  justify-content: center;
}
</style>
